import tkinter as tk

class ToolTip:
    """为Tkinter控件添加悬停提示功能"""
    
    def __init__(self, widget,strategy_info,text,  delay=500, **kwargs):
        self.widget = widget
        self.text = text
        self.strategy_info = strategy_info
        self.delay = delay  # 延迟显示时间（毫秒）
        self.tip_window = None
        self.id = None
        self.x = self.y = 0
        
        # 自定义样式（可选）
        self.bg_color = kwargs.get("bg_color", "#FFFFE0")  # 背景色
        self.fg_color = kwargs.get("fg_color", "black")    # 文本颜色
        self.font = kwargs.get("font", ("Arial", 9))       # 字体
        self.border_width = kwargs.get("border_width", 1)  # 边框宽度
        
        # 绑定事件
        self.widget.bind("<Enter>", self.enter)
        self.widget.bind("<Leave>", self.leave)
        self.widget.bind("<ButtonPress>", self.leave)
        self.widget.bind("<Motion>", self.on_motion)

    def enter(self, event=None):
        self.x = event.x
        self.y = event.y
        self.id = self.widget.after(self.delay, self.show_tip)

    def leave(self, event=None):
        if self.id:
            self.widget.after_cancel(self.id)
        self.hide_tip()

    def on_motion(self, event=None):
        self.x = event.x
        self.y = event.y
        self.hide_tip()
        if self.id:
            self.widget.after_cancel(self.id)
        self.id = self.widget.after(self.delay, self.show_tip)
    
    def setinfo(self,index):
        # print("进入setinfo")
        try:
            # 获取对应索引的列表项内容
            # index = self.widget.nearest(self.y)
            # print("setinfo得到index"+str(index))
            file_name = self.widget.get(index)
            # print("setinfo得到file_name="+str(file_name))
            info = self.strategy_info.get(file_name)
            # print("setinfo得到info="+str(info))
            if info:
                item_dict = info[0]
            infotext = (f"名称：{item_dict.get('name', '')}\n"
                f"描述：{item_dict.get('description', '')}\n"
                f"创建日期：{item_dict.get('createDate', '')}\n"
                f"创建人：{item_dict.get('createBy', '')}\n"
                f"版本：v{item_dict.get('version', '')}")

        except:
            self.text = "getinfo问题"
        return infotext

    def show_tip(self):
        # print("show_tip被触发")
        if self.tip_window:
            return
        # 获取鼠标位置对应的列表项索引
        index = self.widget.nearest(self.y)
        # print("show_tip得到index="+str(index))
        infotext=str(self.setinfo(index))
        # print("show_tip得到infotext=")
        # print(infotext)
        try:                                 
            self.text=infotext
            
            # print("执行了setinfo")
        # 获取对应索引的列表项内容

        except:
            self.text = "显示tip发生了错误"

        if not self.text:
            return

        # 计算提示框位置（相对于鼠标）
        x = self.widget.winfo_pointerx() + 10
        y = self.widget.winfo_pointery() + 10

        # 创建提示窗口
        self.tip_window = tw = tk.Toplevel(self.widget)
        tw.wm_overrideredirect(True)  # 无边框
        tw.wm_geometry(f"+{x}+{y}")

        # 设置提示内容
        label = tk.Label(
            tw, 
            text=self.text,
            bg=self.bg_color,
            fg=self.fg_color,
            font=self.font,
            borderwidth=self.border_width,
            relief=tk.SOLID,
            padx=4,
            pady=2
        )
        label.pack()

    def hide_tip(self):
        tw = self.tip_window
        self.tip_window = None
        if tw:
            tw.destroy()

# 快捷函数：简化ToolTip的创建
def create_tiptool(widget, strategy_info, text="", delay=500, **kwargs):
    # 正确传递参数
    tiptool = ToolTip(widget, strategy_info,text,  delay=delay, **kwargs)
    return tiptool


    
